# Setup -------------------------------------------------------------------
rm(list = ls())
library(haven)


# Function definition -----------------------------------------------------

# Function for running individual bivariate regressions and extracting the coefficients:

indiv.reg.int <- function(formula, data, id, id.var = "ID") {
  if (id %% 1000 == 0) {
    print(paste0("Regression: ", id, "/", max(id.var)))
  }
  fit <- lm(formula, data = data[id.var == id,])
  c(id, coef(fit), sqrt(diag(vcov(fit))))
}



# Execution ---------------------------------------------------------------
# Execute for the 1-year models:

# Set paths:
main <- "placeholder_main"
path_in <- paste0("/Data/114_RPanelRegression_Full_2006_relative_trend.dta")
path_out <- paste0("/Data/114_RPanelRegression_Full_2006_relative_trend_rel.csv")
  
# Load data:
data <- read_dta(file = path_in)

# Calculate regressions:
results <- t(sapply(X = unique(data$key), 
                    FUN = indiv.reg.int, 
                    formula = log_p_emplAft6M_0M_In ~ log_shareUnemp_rel + trend_rel, 
                    data = data, 
                    id.var = data$key))
# Fix column names:
colnames(results) <- c("key", "beta_0", "beta_1", "beta_t", "beta_0_se", "beta_1_se", "beta_t_se")

# Save to csv:
write.csv(results, file = path_out)
